import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Parser implements IParser {

	private int firstWhiteSpace(String str) {
		int result = 0;
		for (int i = 0; i < str.length(); i++) {
			if (Character.isWhitespace(str.charAt(i))) {
				return i;
			}
		}
		return result;
	}

	@Override
	public void runFirstPass(Reader in, IListing listingTable,
			ISymbolTable symbolTable) throws Exception {
		Scanner input = new Scanner(in);
		String line;
		int count = 1;
		while (input.hasNext()) {
			line = input.nextLine();
			String label = "";
			Mnemonic mnemonic = Mnemonic.NONE;
			int locCount = 0;

			Boolean isSymbol = false;
			// Checks if there is a label
			if (!Character.isWhitespace(line.charAt(0))) {
				int space = this.firstWhiteSpace(line);
				label = line.substring(0, space);
				line = line.substring(space);
				locCount = listingTable.getCurrentLC();
				isSymbol = true;
			}

			// Remove spaces between label and mnemonic
			line = line.trim();
			int spacePos = this.firstWhiteSpace(line);
			mnemonic = Mnemonic.valueOf(line.substring(0, spacePos)
					.toUpperCase());
			line = line.substring(spacePos);

			// Remove spaces between mnemonic and operands
			line = line.trim();

			// Operands will be before semicolon and comments are after the
			// semi-colon
			int semiColonPos = line.indexOf(';');
			String[] inOps = line.substring(0, semiColonPos).split(",");
			List<Operand> ops = new ArrayList<Operand>();
			for (String op : inOps) {
				Operand.Keyword kw = Operand.Keyword.valueOf(op.substring(0, 2)
						.toUpperCase());
				String value = op.substring(3);
				ops.add(new Operand(kw, value));
			}

			//
			String comment = line.substring(semiColonPos + 1).trim();
			listingTable.addLine(count, label, comment, mnemonic, ops);
			if (isSymbol) {
				String str = "";
				if (mnemonic.equals(Mnemonic.EQU)
						|| mnemonic.equals(Mnemonic.EQUE)) {
					str = ops.get(0).getString();
				}
				symbolTable.add(label, locCount, mnemonic.toString(), str);
			}
			count++;
		}
	}

	public static void main(String[] args) throws Exception {
		IListing listTable = new Listing();
		ISymbolTable symTable = new SymbolTable();
		Parser p = new Parser();
		Reader in = new FileReader("test.txt");
		p.runFirstPass(in, listTable, symTable);
	}
}
